/*
RC Joystick
by KaiK (https://code.google.com/p/kaik-rcjoystick)

This code uses a Arduino Mega (1280 or 2560) and a USB Host Shield V2 to read a USB joystick 
(in my case logitech wingman attack 2) and create a 8 channel ppm signal for injecting into
trainer port of rc (e.g. TH9x) or directly using only a rc module.
  
DISCLAIMER:
  With this design, including both the hardware & software I offer no guarantee that it is bug
  free or reliable. So, if you decide to build one and your plane, quad etc crashes and/or causes
  damage/harm to you, others or property then you are on your own. This work is experimental.

Some code fragments as well as the disclaimer were adapted from Ian Johnston (www.ianjohnston.com). I found his great project, but wanted to code something lighter/easier.
  
*/


#include <avr/pgmspace.h>

#include <avrpins.h>
#include <max3421e.h>
#include <usbhost.h>
#include <usb_ch9.h>
#include <Usb.h>
#include <usbhub.h>
#include <avr/pgmspace.h>
#include <address.h>
#include <hid.h>
#include <hiduniversal.h>

#include "hidjoystickrptparser.h"

#include <printhex.h>
#include <message.h>
#include <hexdump.h>
#include <parsetools.h>

#include "config.h"

USB                                             Usb;
USBHub                                          Hub(&Usb);
HIDUniversal                                    Hid(&Usb);
JoystickEvents                                  JoyEvents;
JoystickReportParser                            Joy(&JoyEvents);

extern int PPM_array[9];

void setup()
{
  pinMode(outPinPPM, OUTPUT);      // set as output
  
  // Initialize PPM channel array
  char i=0;
  for(i=0; i<8; i++) { PPM_array[i] = pulseMin; }
  PPM_array[i] = -1;   // Mark end
  
  // TIMER INFO: Timer 1 = PPM Gen (11,12), Timer 2 = USB Host (9,10), Timer 3 = ISR
  
  // Initialise ISR Timer 1 - PPM generation
  TCCR1A = B00110001;     // Compare register B used in mode 3
  TCCR1B = B00010010;     // WGM13 & CS11 set to 1
  //TCCR1C = B00000000;     // All set to 0
  TIMSK1 = B00000010;     // Interrupt on compare B
  TIFR1  = B00000010;     // Interrupt on compare B
  OCR1A = PPMFreq_uS;     // PPM frequency
  OCR1B = Fixed_uS;       // PPM off time (lo padding)
  if (InvertPPM == 1) { TCCR1A = B00100001; }
  
  Serial.begin( 115200 );
  Serial.println("Start");

  if (Usb.Init() == -1)
      Serial.println("OSC did not start.");
      
  delay( 200 );

  if (!Hid.SetReportParser(0, &Joy))
      ErrorMessage<uint8_t>(PSTR("SetReportParser"), 1  ); 
}

void loop()
{
    Usb.Task();
}
